﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using Task.Util;
using System.Net.Cache;


namespace Task.Quartz.Execute.Holytax
{
    public class InvoiceExchangeHelper
    {
        /// <summary>
        /// 上传zip文件
        /// </summary>
        /// <param name="exEntity">与平台交互需要使用的参数实体</param>
        /// <param name="arrZips">需要上传的zip文件列表</param>
        /// <returns>是否上传成功</returns>
        public static bool UploadZips(ExchangeEntity exEntity, string zipFileName)
        {
            try
            {
                System.GC.Collect();
                System.Net.ServicePointManager.DefaultConnectionLimit = 100;
                HttpWebRequest httpRequest = WebRequest.Create(exEntity.URL) as HttpWebRequest;
                httpRequest.KeepAlive = false;
                httpRequest.ContentType = "text/html";
                httpRequest.Headers["NSR"] = exEntity.Account;
                httpRequest.Headers["PWD"] = exEntity.Password;
                httpRequest.Headers["NSRSBH"] = exEntity.EntCode;
                httpRequest.Headers["FORMAT"] = "zip";
                httpRequest.ProtocolVersion = new Version("1.0");
                httpRequest.UserAgent = "Mozilla/3.0 (compatible;Indy library) ";
                httpRequest.Accept = "text/html, */*";
                httpRequest.Method = "POST";
                httpRequest.Timeout = 5 * 60 * 1000;
                //获得后台设置的代理，指定http代理
                if (exEntity.IsProxy.Equals("1"))
                {
                    WebProxy proxy = new WebProxy(exEntity.ProxyIp, int.Parse(exEntity.ProxyPort));
                    proxy.Credentials = new NetworkCredential(exEntity.AuthUID, exEntity.AuthPassword);
                    httpRequest.Proxy = proxy;
                }

                //这个在Post的时候，一定要加上，如果服务器返回错误，他还会继续再去请求，不会使用之前的错误数据，做返回数据
                httpRequest.ServicePoint.Expect100Continue = false;
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                httpRequest.CachePolicy = noCachePolicy;

                byte[] arrInvoiceSend = null;
                HttpWebResponse httpResponse = null;

                arrInvoiceSend = ZipHelper.ReadFromZipFile(zipFileName);

                using (Stream requestStream = httpRequest.GetRequestStream())
                {
                    requestStream.Write(arrInvoiceSend, 0, arrInvoiceSend.Length);
                    requestStream.Flush();
                    requestStream.Close();
                }
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                if (httpResponse.StatusCode != HttpStatusCode.OK)
                {
                    exEntity.ErrorDesc = String.Format("POST failed {0}", httpResponse.StatusCode);
                    return false;
                }
                string strResult = httpResponse.Headers["result"];
                switch (strResult)
                {
                    case "1":
                        break;
                    case "2":
                        exEntity.ErrorDesc = string.Format(@"无此纳税人或还没有进行开户[{0}]。", 3);
                        break;
                    case "3":
                        exEntity.ErrorDesc = string.Format(@"用户名或密码错误[{0}]。", 3);
                        break;
                    case "4":
                        exEntity.ErrorDesc = "上传失败[" + 4 + "]。";
                        break;
                }

                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
                if (httpRequest != null)
                {
                    httpRequest.Abort();
                }

                if (!strResult.Equals("1"))
                {
                    return false;
                }
                return true;
            }
            catch (Exception err)
            {
                exEntity.ErrorDesc = err.Message;
                return false;
            }
        }

        /// <summary>
        /// 下载zip文件
        /// </summary>
        /// <param name="exEntity">与平台交互需要使用的参数实体</param>
        /// <param name="zipFileName">下载到的文件全名称</param>
        /// <returns></returns>
        public static bool DownloadZips(ExchangeEntity exEntity, string zipFileName)
        {
            try
            {
                System.GC.Collect();
                System.Net.ServicePointManager.DefaultConnectionLimit = 100;
                HttpWebRequest httpRequest = WebRequest.Create(exEntity.URL) as HttpWebRequest;
                httpRequest.KeepAlive = false;
                httpRequest.ContentType = "text/html";
                httpRequest.ContentLength = 0;
                httpRequest.Headers["NSR"] = exEntity.Account;
                httpRequest.Headers["PWD"] = exEntity.Password;
                httpRequest.Headers["NSRSBH"] = exEntity.EntCode;
                httpRequest.Headers["FORMAT"] = "zip";
                httpRequest.Headers["BDATE"] = exEntity.StartDate;
                httpRequest.Headers["EDATE"] = exEntity.EndDate;
                httpRequest.ProtocolVersion = new Version("1.0");
                httpRequest.UserAgent = "Mozilla/3.0 (compatible;Indy library) ";
                httpRequest.Accept = "text/html, */*";
                httpRequest.Method = "POST";
                httpRequest.Timeout = 5 * 60 * 1000;

                //获得后台设置的代理，指定http代理
                if (exEntity.IsProxy.Equals("1"))
                {
                    WebProxy proxy = new WebProxy(exEntity.ProxyIp, int.Parse(exEntity.ProxyPort));
                    proxy.Credentials = new NetworkCredential(exEntity.AuthUID, exEntity.AuthPassword);
                    httpRequest.Proxy = proxy;
                }

                //这个在Post的时候，一定要加上，如果服务器返回错误，他还会继续再去请求，不会使用之前的错误数据，做返回数据
                httpRequest.ServicePoint.Expect100Continue = false;
                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                httpRequest.CachePolicy = noCachePolicy;

                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                if (httpResponse.StatusCode != HttpStatusCode.OK)
                {
                    exEntity.ErrorDesc = String.Format("POST failed {0}", httpResponse.StatusCode);
                    return false;
                }
                string strResult = httpResponse.Headers["result"];
                switch (strResult)
                {
                    case "1":
                        using (System.IO.Stream responseStream = httpResponse.GetResponseStream())
                        {
                            System.IO.FileStream fs = System.IO.File.Create(zipFileName);
                            int size = 0;
                            byte[] buffer = new byte[4096];
                            do
                            {
                                size = responseStream.Read(buffer, 0, 4096);
                                fs.Write(buffer, 0, size);
                            }
                            while (size > 0);

                            fs.Flush();
                            fs.Close();
                            responseStream.Close();
                        }
                        break;
                    case "2":
                        exEntity.ErrorDesc = "无此纳税人或还没有进行开户[" + 2 + "]。";
                        break;
                    case "3":
                        exEntity.ErrorDesc = "用户名或密码错误[" + 3 + "]。";
                        break;
                    case "4":
                        exEntity.ErrorDesc = "下载失败[" + 4 + "]。";
                        break;
                }

                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
                if (httpRequest != null)
                {
                    httpRequest.Abort();
                }
                if (!strResult.Equals("1"))
                {
                    return false;
                }
                return true;
            }
            catch (Exception err)
            {
                exEntity.ErrorDesc = err.Message;
                return false;
            }
        }
    }
}
